<?php

namespace App\Http\Middleware;

use App\Models\ApiResult;
use App\Services\Base\CacheService;
use App\Services\Base\MsgService;
use Closure;
use Illuminate\Support\Facades\Log;


class CheckBearerToken
{
    public function handle($request, Closure $next)
    {
        $token = $request->bearerToken();
        if ($token) {
            $exist = CacheService::hGet(R_LOGIN_TOKEN_INFO, $token);
            if (!$exist) {
                Log::channel('token')->info("token invalid -" . "url:" . $request->url() . ",header:" . json_encode($request->header()) . ",body:" . json_encode($request->all()));
                return response()->json(ApiResult::failure(401, MsgService::toMessage(401)));
            } else if (R_REDIS_ERROR === $exist) {
                Log::channel('token')->info("redis error -" . "url:" . $request->url() . ",header:" . json_encode($request->header()) . ",body:" . json_encode($request->all()));
                return response()->json(ApiResult::failure(401, MsgService::toMessage(401)));
            } else {
                $expired = config('comm.token.expired');
                if ($expired) {
                    $exist = json_decode($exist, true);
                    if ($expired * 60 + $exist['login_time'] < time()) {
                        Log::channel('token')->info("token expired -" . "url:" . $request->url() . ",header:" . json_encode($request->header()) . ",body:" . json_encode($request->all()));
                        CacheService::hDel(R_LOGIN_TOKEN_INFO, $token);
                        return response()->json(ApiResult::failure(401, MsgService::toMessage(401)));
                    }

                }
            }
        } else {
            Log::channel('token')->info("no token -" . "url:" . $request->url() . ",header:" . json_encode($request->header()) . ",body:" . json_encode($request->all()));
            return response()->json(ApiResult::failure(401, MsgService::toMessage(401)));
        }

        return $next($request);
    }


}
